package com.jl.juc.completablefuture;

import lombok.AllArgsConstructor;
import lombok.Data;

import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * ComplatableFuture实战
 */
public class GetInfoDemo {

    public static void main(String[] args) {
        List<Mall> malls = Stream.of(
                new Mall("京东"),
                new Mall("淘宝"),
                new Mall("平多多")
        ).collect(Collectors.toList());

        long start = System.currentTimeMillis();
        getPriceFromMallList(malls, "荒天帝");
        long end = System.currentTimeMillis();
        System.out.println(end - start);

    }

    public static void getPriceFromMallList(List<Mall> malls, String productName){

        List<String> result = malls.stream().map(i -> CompletableFuture.supplyAsync(() -> {
            double price = i.getPrice(productName);
            String s = String.format("%s 在 %s的价格是%.2f", productName, i.getPlatName(), price);
            return s;
        }))
        .collect(Collectors.toList()).stream() //必须再转换一次，否则时间还是6秒
        .map(i -> i.join()).collect(Collectors.toList());

        result.forEach(i-> System.out.println(i));
    }

}


@Data
@AllArgsConstructor
class Mall{

    /**
     * 平台名称
     */
    private String platName;

    public double getPrice(String productName){
        try {
            TimeUnit.SECONDS.sleep(2);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return ThreadLocalRandom.current().nextDouble() * 2;
    }


}

